#!/usr/bin/env bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source $DIR/../../lib/shell/common.sh

function server_kill() {
    server_down="kill -9 \`pidof iperf3\` &>/dev/null"
    $ESSH $lts_ip $server_down || return 1
    return 0
}

function server_run() {
    echo "start server listen"
    server_kill
    server_cmd="iperf3 -sD"
    $ESSH $lts_ip $server_cmd &
    if [ $? -eq 0 ]; then
        echo "server listen success"
        sleep 3
        return 0
    else
        echo "server listen failed"
        return 1
    fi
}

function client_run() {
    echo "start client connect"
    client_cmd="iperf3 -t $IPERF3_RUNTIME -i $IPERF3_INTERVAL -P $IPERF3_PROCESS_NUM -c $lts_ip -B $sut_ip"
    run_cmd "$client_cmd" > $IPERF3_LOG &
    if [ $? -eq 0 ]; then
        echo "client connect success"
        return 0
    else
        echo "client connect failed"
        return 1
    fi
}

function bandwidth_check_results(){
    if test ! -f "$IPERF3_LOG"; then
        echo "no log file"
        return 1
    fi

    sums=$(cat $IPERF3_LOG | grep "SUM" | awk '{print $6}')

    theory=$(ethtool $cur_interface 2>/dev/null | grep "Speed" | awk '{print $2}' | sed 's/Mb\/s//')
    threshold=$(echo "scale=2; $theory * 0.9 / 1000" | bc )

    for sum in $sums;do
        if (( $(echo "$sum < $threshold" | bc -l) )); then
            echo -e "Practical Bandwidth is lower than 90% of the theoritical Bandwidth!"
            echo -e "Please ensure that your machines are directly connected."
            return 1
        fi
    done

    return 0
}

function bandwidth_test(){
	check_cmd "iperf3"

    IPERF3_LOG=bandwidth_test_log
    [ -z "$LTS_IPADDRESS" ] && { echo "Error: LTS IP are required, but none are given";exit 1; }
    lts_ip=$(echo $LTS_IPADDRESS | awk '{print $1}')
    
    server_run
    [ $? -ne 0 ] && return 1

    # clean all iperf3 processes
    if ps -ef|grep iperf3|grep -w $IPERF3_PORT >/dev/null 2>&1;then
        kill -9 `ps -ef|grep iperf3|grep -w $IPERF3_PORT|awk '{print $2}'`
    fi

    [ -n "$INTERFACES" ] || { echo "no interface found";return 1; }
    err=""
    ip_pair=""
    for cur_interface in $INTERFACES; do
        echo $cur_interface
        sut_ip=""
        sut_ip=$(ip addr show $cur_interface | grep -w 'inet' | awk '{print $2}' | awk -F'/' '{print $1}')
        [ -n "$sut_ip" ] || continue

        ping -I $sut_ip $lts_ip -w5 >/dev/null 2>&1 || continue

        ip_pair="pingable ip pair $sut_ip $lts_ip"
        echo $ip_pair
        client_run
        [ $? -ne 0 ] && { err='error'; break; }
        wait
        bandwidth_check_results || { err='error'; break; }
    done

    if test -f "$IPERF3_LOG"; then
        rm -rf $IPERF3_LOG
    fi

    server_kill || return 1

    [ -n "$ip_pair" ] || {
        echo -e "no valid ip pair for bare devices, please check if your devices are bonded";
        return 1; 
    }

    [ -n "$err" ] && return 1

    return 0
}